<template>
  <div class="card-modal">
    <BasicModal
      title="激活卡密"
      to=".card-modal"
      @register="CardActiveModalRegister"
      @confirm="handleSubmit"
      @after-leave="handleLeave"
    >
      <n-form ref="activeCardRef" v-model:model="ActiveCardForm" size="large">
        <n-form-item path="content" :rule="[{ required: true, validator: checkCard, trigger: 'blur' }]">
          <n-input
            v-model:value="ActiveCardForm.content"
            class="h-12"
            :allow-input="noSideSpace"
            placeholder="请输入卡密"
          />
        </n-form-item>
      </n-form>
    </BasicModal>
  </div>
</template>

<script setup>
import { defineAsyncComponent, getCurrentInstance, reactive } from 'vue'
import { useModal } from '@/components/Modal/useModal'
import { ActiveCard } from '@/api/cardApi'
import { useUserStore } from '@/store'
import { useDialog } from 'naive-ui'
import { noSideSpace } from '@/utils'

const { proxy } = getCurrentInstance()
const BasicModal = defineAsyncComponent(() => import('@cmps/Modal/BasicModal.vue'))
const userStore = useUserStore()
const dialog = useDialog()

const ActiveCardForm = reactive({
  content: '',
})

const [
  CardActiveModalRegister,
  { openModal: openCardActiveModal, closeModal: closeCardActiveModal, setModalLoading: changeSubmitLoading },
] = useModal({})

const checkCard = (rules, content) => {
  if (!content) {
    return new Error('卡密不能为空')
  }
  const reg = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[8|9|aA|bB][0-9a-f]{3}-[0-9a-f]{12}$/i
  if (!reg.test(content)) {
    return new Error('卡密格式不正确')
  } else {
    return true
  }
}

const handleSubmit = () => {
  proxy.$refs.activeCardRef.validate(async validate => {
    if (validate) return false
    changeSubmitLoading(true)
    const result = await ActiveCard({ content: ActiveCardForm.content })
    if (result.statusCode === 200) {
      closeCardActiveModal()
      dialog.success({
        title: '兑换卡密成功',
        content: `您成功使用【${result.data.name}】获得会员 ${result.data.day} 天`,
      })
      await userStore.getUserInfo()
    }
    changeSubmitLoading(false)
  })
}

const handleLeave = () => {
  ActiveCardForm.content = ''
}

const openCardActive = () => {
  openCardActiveModal()
}

defineExpose({
  openCardActive,
})
</script>

<style lang="less" scoped>
.card-modal {
  &:deep(.n-modal-container) {
    .n-dialog__content {
      margin-top: 10px;
    }
  }
}
</style>
